<?php
/**
 * 
 * app 21点
 * @author will
 *
 */
class App_21 {
	/**
	 * 获取排行榜
	 * @param <int> $offset
	 * @param <int> $limit
	 */
	public static function getTopList($type , $offset = 0 , $limit = 10) {
		$Db = loadDB();
		
		$result = $Db->getAll("SELECT * FROM `app_21_gain` ORDER BY `{$type}` DESC LIMIT {$offset} , {$limit}");
		return $result;
	}
	
	/**
	 * 获取已开通的牌局
	 * @param <int> $uin	如果$uin是0，则随机取N条
	 * @param <int> $offset
	 * @param <int> $limit
	 */
	public static function getUserStateList($uin , $offset = 0 , $limit = 50) {
		$Db = loadDB();
		
		$result = $Db->getAll("SELECT * FROM `app_21_state` WHERE `uin` = {$uin} ORDER BY `id` LIMIT {$offset} , {$limit}");
		if(empty($result)) return array();
		
		foreach($result as $k => $row) {
			$result[$k]['state'] = unserialize($row['state']);
		}
		
		return $result;
	}
	
	/**
	 * 随机获取用户已可应战的牌局
	 * @param <int> $limit
	 */
	public static function getRandStateList() {
		$Db = loadDB();
	
		$result = $Db->getAll("SELECT * FROM `app_21_state`,`app_21_gain` WHERE `turn` = 1 AND app_21_state.uin=app_21_gain.uin ORDER BY RAND() DESC LIMIT 10");

		if(empty($result)) return array();
		foreach($result as $k => $row) {
			$result[$k]['state'] = unserialize($row['state']);
		}
		
		return $result;
	}
	
	/**
	 * 获取多个用户称号
	 * @param <array> $uins
	 * @param <array> $gains
	 */
	public static function getRanks($uins , $gains = false) {
		if(empty($gains)) {
			$uins_str = implode(',' , $uins);
			
			$Db = loadDB();
			$result = $Db->getAll("SELECT `uin` , `gain` FROM `app_21_gain` WHERE `uin` IN '{$uins_str}'");
			
			$gains = array();
			if(!empty($result)) {
				foreach($result as $row) {
					$gains[$row['uin']] = $row['gain'];
				}
			}
		}
		
		$return_arr = array();
		foreach($uins as $uin) {
			$gain = empty($gains[$uin]) ? 0 : $gains[$uin];
			$return_arr[$uin] = self::getRank($uin , $gain);
		}
		
		return $return_arr;
	}
	
	
	/**
	 * 获取单个用户称号
	 * Enter description here ...
	 */
	public static function getRank($uin , $gain = false) {
		// 如果没有传进来数据，则从数据库获取
		if($gain === false) {
			$result = self::getGain($uin);
			
			if(empty($result)) $gain = 0;
			else $gain = $result['gain'];
		}
		
		if($gain >= 10000000) {
			return array('level' => 12 , 'name' => '赌圣');
		} else if($gain >= 5000000) {
			return array('level' => 11 , 'name' => '全球巨头');
		} else if($gain >= 200000) {
			return array('level' => 10 , 'name' => '亚洲富豪');
		} else if($gain >= 100000) {
			return array('level' => 9 ,  'name' => '内地富豪');
		} else if($gain >= 50000) {
			return array('level' => 8 ,  'name' => '大土豪');
		} else if($gain >= 20000) {
			return array('level' => 7 ,  'name' => '地主');
		} else if($gain >= 10000) {
			return array('level' => 6 ,  'name' => '财主');
		} else if($gain >= 5000) {
			return array('level' => 5 ,  'name' => '富农');
		} else if($gain >= 1000) {
			return array('level' => 4 ,  'name' => '中农');
		} else if($gain >= 100) {
			return array('level' => 3 ,  'name' => '贫农');
		} else if($gain >= 0) {
			return array('level' => 2 ,  'name' => '赤脚');
		} else {
			return array('level' => 1 ,  'name' => '送财童子');
		}
	}
	
	/**
	 * 随机发排
	 * @param <int> $num 随机张数
	 */
	public static function deal($num = 1) {
		if($num == 1) {
			return rand(1 , 13);
		}
		
		$return_nums = array();
		for($i = 0 ; $i < $num ; $i++) {
			$return_nums[] = rand(1 , 13);
		}
		
		return $return_nums;
	}
	
	/**
	 * 计算牌的总和
	 * @param <array> $cards
	 */
	public static function sum($cards) {
		$sum = 0;
		foreach($cards as $card) {
			if($card > 10) $sum += 10;
			else $sum += $card;
		}
		return $sum;
	}
	
	/**
	 * 牌的数字转换为 A 2 3 4 .... 10 J Q K
	 * @param <int|array> $num
	 */
	public static function num2card($num) {
		$map = array(
			1 => 'A',
			11 => 'J',
			12 => 'Q',
			13 => 'K',
		);
		
		if(!is_array($num)) {
			$n = $num;
			return isset($map[$n]) ? $map[$n] : $n;
		}
		
		$return_cards = array();
		foreach($num as $k => $n) {
			$return_cards[$k] = isset($map[$n]) ? $map[$n] : $n;
		}
		return $return_cards;
	}
	
	/**
	 * 记录收入榜
	 * @param <int> $uin
	 * @param <int> $num
	 * @param <int> $is_win 是否胜利，如果不传，则按 num 的正负来决定
	 */
	public static function updateGain($uin , $num , $is_win = null) {
		// 先获取一下数据，保证这个用户在数据库里有数据
		$old_data = self::getGain($uin);
		
		// 修改数据
		$Db = loadDB();
		
		$gain = $old_data['gain'] + $num;
		$total = $old_data['total'] + 1;
		if($is_win === null) {
			$is_win = $num > 0 ? true : false;
		}
		$win = $is_win ? $old_data['win'] + 1 : $old_data['win'];
		$rate = sprintf('%.4f' , $win / $total) * 10000;
		
		$query_data = array(
			'gain' => $gain,
			'total' => $total,
			'win' => $win,
			'rate' => $rate,
			'time' => isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time(),
		);
		
		$success = $Db->doUpdate('app_21_gain' , $query_data , "`uin` = {$uin}");
		
		return $success ? 0 : 100101;
	}
	
	/**
	 * 输牌
	 * @param <int> $uin
	 * @param <int> $id
	 * @param <int> $lose_uin
	 * @param <array> $state
	 */
	public static function lose($uin , $id , $lose_uin , &$state) {
		if(empty($state)) {
			$state = self::getState($uin , $id);
		}
		
		// 牌局不存在
		if(empty($state)) {
			return 100103;
		}
		
		$stake = $state['stake'];
		
		// 给用户加钱
		if(empty($state['guest_uin'])) {
			// 主人自己爆了，不用给任何人加钱
			$code = 0;
		} else if($lose_uin == $state['uin']) {
			// 主人输，给客人加钱
			loadLib('Currency');
			$code = Currency::update('app_21' , $state['guest_uin'] , $stake * 2);
		} else {
			// 客人输了，给主人加钱
			loadLib('Currency');
			$code = Currency::update('app_21' , $state['uin'] , $stake * 2);
		}
		
		if($code !== 0) {
			return $code;
		}
		
		// 删除牌局
		$code = self::delState($uin , $id);
		if($code !== 0) {
			return $code;
		}
		
		// 更新排行榜
		$gain = $stake;
		if(empty($state['guest_uin'])) {
			
		} else if($lose_uin == $state['uin']) {
			// 客人赢了
			self::updateGain($state['guest_uin'] , $gain);
		} else {
			// 主人赢了
			self::updateGain($state['uin'] , $gain);
		}
		
		self::updateGain($lose_uin , 0 - $gain);
		
		return 0;
	}
	
	/**
	 * 获取收入榜
	 * @param <int> $uin
	 * @param <boolean> $insert 是否在不存在时，新写入数据
	 */
	public static function getGain($uin , $insert = true) {
		$Db = loadDB();
		$result = $Db->getOne("SELECT * FROM `app_21_gain` WHERE `uin` = " . $uin);
		
		// 如果金库数据不存在，则新写入一条数据
		if($insert && $result === false) {
			$query_data = array(
				'uin' => $uin,
				'gain' => 0,
				'total' => 0,
				'win' => 0,
				'rate' => 0,
				'time' => 0,
			);
			$Db->doInsert('app_21_gain' , $query_data);
			
			$result = $query_data;
		}
		
		return $result;
	}
	
	/**
	 * 获取牌局
	 * @param <int> $uin
	 * @param <int> $id
	 */
	public static function getState($uin , $id) {
		$Db = loadDB();
		
		$result = $Db->getOne("SELECT * FROM `app_21_state` WHERE `uin` = {$uin} AND `id` = {$id}");
		if(empty($result)) return array();
		
		$result['state'] = unserialize($result['state']);
		
		return $result;
	}
	
	/**
	 * 删除牌局
	 * @param <int> $uin
	 * @param <int> $id
	 */
	public static function delState($uin , $id) {
		$Db = loadDB();
		
		$success = $Db->query("DELETE FROM `app_21_state` WHERE `uin` = {$uin} AND `id` = {$id}");
		
		return $success ? 0 : 100105;
	}
	
	/**
	 * 存储当前牌局
	 * @param <int> $uin
	 * @param <int> $id 传入了则为修改，否则为新增
	 * @param <int> $turn 0 => 主人 , 1 => 客人
	 * @param <array> $owner_cards	主人的牌
	 * @param <array> $guest_cards	客人的牌
	 * @param <int> $stake	赌注
	 */
	public static function recordState($uin , &$id , $guest_uin , $turn , $owner_cards , $guest_cards , $stake) {
		$Db = loadDB();
		
		// 按格式打包，暂时是用 serialize
		$state = array(
			'owner_cards' => $owner_cards,
			'guest_cards' => $guest_cards,
		);
		$state = serialize($state);
		
		$time = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time();
		$query_data = array(
			'guest_uin' => $guest_uin,
			'turn' => $turn,
			'state' => $state,
			'stake' => $stake,
			'time' => $time,
		);
		
		if($id > 0) {
			// 修改
			$success = $Db->doUpdate('app_21_state' , $query_data , "`uin` = {$uin} AND `id` = {$id}");
		} else {
			// 新增
			
			$id = $time;		// 分配一个id
			$query_data['id'] = $id;
			$query_data['uin'] = $uin;
			
			$success = $Db->doInsert('app_21_state' , $query_data);
		}
		
		return $success ? 0 : 100102;
	}
	/**
	 * 修改state
	 */
	public static function getUpstate($uin, $id, $state){
		$Db=loadDB();
		$is_state = serialize($state);
		$update_data = array(
			'state' => $is_state,
		);
		
		$success = $Db->doUpdate('app_21_state' , $update_data , "`uin` = {$uin} AND `id` = {$id}");
		//print_r($success);
		return $success ? 0 : 523;
	} 
}


# end of script

